/********************
点击考核名称后的指标填报弹窗
** */
<template>
  <el-dialog
    width="80%"
    title="结果评审"
    :close-on-click-modal="false"
    :visible.sync="visible"
    top="8vh"
    @close="closeDialog()"
  >
    <el-form
      ref="dataForm"
      :model="dataForm"
      label-position="right"
      label-width="120px"
      @keyup.enter.native="dataFormSubmit()"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="考核名称" prop="name" style="width:60%">
            <span>{{dataForm.name}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="周期名称" prop="date" style="width:60%">
            <span>{{dataForm.period}}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="考核时间" prop="sname" style="width:60%">
            <span>{{dataForm.assessBeginTime?dataForm.assessBeginTime.slice(0,10):""}}--{{dataForm.assessEndTime?dataForm.assessEndTime.slice(0,10):''}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="dataForm.type==0?'被考核人':'被考核机构'" style="width:60%;">
            <span v-if="dataForm.type==0">
              <span v-for="it in dataForm.assessTarget" :key="it">{{it}},</span>
            </span>
            <span v-else>
              <span v-for="it in dataForm.assessDeptName" :key="it">{{it}},</span>
            </span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="height: 10px; border-top: 1px solid #b0bde2"></div>
    <div class="tabBox">
      <div class="btnBox">
        <div>
          <el-tooltip effect="dark" content="选择指标" placement="top">
            <el-button icon="el-icon-plus" type="success" circle @click="showTarLibrary"></el-button>
          </el-tooltip>
          <el-button
            @click="deleteIndexRow"
            :disabled="canDelete"
            type="danger"
            icon="el-icon-delete"
            circle
          ></el-button>
        </div>
        <!--<div>
          <el-button @click="repeatTarget" type="primary">复用指标</el-button>
        </div>-->
      </div>
    </div>
    <el-row>
      <el-table
        style="width: 100%;margin-top:20px"
        :data="dataList"
        border
        stripe
        header-align="center"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" fixed="left"></el-table-column>
        <el-table-column type="index" width="55" label="序号" fixed="left" align="center"></el-table-column>
        <el-table-column prop="type" align="center" label="指标类别" width="120" fixed="left"></el-table-column>
        <el-table-column prop="name" align="center" label="指标名称" show-overflow-tooltip width="120"></el-table-column>
        <el-table-column prop="weight" align="center" label="权重(%)">
          <template slot-scope="scope">
            <span v-if="scope.row.editFlag == 1">
             <!-- <el-form :model="scope.row" :rules="rules">
               <el-form-item prop="weight">
                  <el-input v-model.number="scope.row.weight"></el-input>
               </el-form-item>
            </el-form>-->
              <el-input
                v-model.number="scope.row.weight"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/^\./g, '').replace(/\.{2,}/g, '.').replace(/(\.\d+)\./g, '$1').replace(/^0+(\d)/, '$1').replace(/(\d{15})\d*/, '$1').replace(/(\.\d{2})\d*/, '$1')"
              ></el-input>
            </span>
            <span v-else>
                  <span>{{scope.row.weight}}</span>
            </span>
          </template>

        </el-table-column>
        <el-table-column prop="targetValue" align="center" label="目标值" min-width="120">
          <template slot-scope="scope">

              <!--<el-input v-model="scope.row.targetValue"
                        :rows="1"
                        type="textarea"></el-input>-->
            <el-input
              :rows="1"
              type="textarea"
              v-model="scope.row.targetValue"
              oninput="value=value.replace(/[^\d.]/g, '').replace(/^\./g, '').replace(/\.{2,}/g, '.').replace(/(\.\d+)\./g, '$1').replace(/^0+(\d)/, '$1').replace(/(\d{15})\d*/, '$1').replace(/(\.\d{2})\d*/, '$1')"
              @blur="getScoreAdd(scope.row, scope.$index)"
              placeholder="目标值"
            ></el-input>
          </template>

        </el-table-column>
        <el-table-column prop="finishValue" align="center" label="完成值" min-width="120">
          <template slot-scope="scope">
            <span >
            <!--  @blur="getScoreAdd(scope.row, scope.$index)"-->
               <!--<el-input  :rows="1"
                          type="textarea"
                          v-model.lazy="scope.row.finishValue"  ></el-input>-->
              <!--                 oninput="value=value.replace(/[^\d.]/g, '').replace(/^\./g, '').replace(/\.{2,}/g, '.').replace(/(\.\d+)\./g, '$1').replace(/^0+(\d)/, '$1').replace(/(\d{15})\d*/, '$1').replace(/(\.\d{2})\d*/, '$1')"-->
               <el-input
                 :rows="1"
                 type="textarea"
                 v-model="scope.row.finishValue"
                 oninput="value=value.replace(/[^\-\d.]/g, '').replace(/^\./g, '').replace(/\.{2,}/g, '.').replace(/(\.\d+)\./g, '$1').replace(/(-)\./g, '$1').replace(/\-{2,}/g, '-').replace(/(\d+|\.)-/g, '$1').replace(/-(0){2,}/g, '$1').replace(/(-)0+(\d+)/g, '$1$2').replace(/^0+(\d)/, '$1').replace(/(\d{15})\d*/, '$1').replace(/(\.\d{2})\d*/, '$1')"
                 @blur="getScoreAdd(scope.row, scope.$index)"
                 placeholder="完成值"
               ></el-input>
            </span>

          </template>
        </el-table-column>

        <el-table-column prop="score" align="center" label="得分" min-width="90">
          <template slot-scope="scope">
           <!-- <el-form :model="scope.row" :rules="rules">
              <el-form-item prop="score">
                <el-input v-model.number="scope.row.score"></el-input>
              </el-form-item>
            </el-form>-->
            <el-input v-model="scope.row.score"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="formula" align="center" label="计算公式" show-overflow-tooltip width="120"></el-table-column>

        <el-table-column prop="unit" align="center" label="单位" show-overflow-tooltip></el-table-column>
        <el-table-column prop="completeValue" align="center" label="完成值获取方式" show-overflow-tooltip width="150">
          <template slot-scope="scope">
            <el-select
              @change="$set(scope.row, scope.row.completeValue, $event)"
              :clearable="true"
              v-model="scope.row.completeValue"
              placeholder="请选择"
            >
              <el-option
                v-for="item in dataFromList"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="provideRealName"
          align="center"
          label="数据提供部门/人"
          show-overflow-tooltip
          width="150"
        >
          <template slot-scope="scope">
            <span
              v-if="scope.row.editFlag == 1"
              style="color:blue"
              @click="showDataProvide(scope.row,scope.$index)"
            >
              <span
                style="color:blue"
                v-if="scope.row.isLiaison == 0"
              >
                 {{scope.row.provideRealName}}
                 <i class="el-icon-edit-outline"></i>
              </span>
                <span
                  v-else
                  style="color:blue"
                  @click="showDataProvide(scope.row,scope.$index)"
                >
                {{scope.row.provideDeptName}}
                <i class="el-icon-edit-outline"></i>
              </span>

            </span>
            <span v-else >
              {{scope.row.provideDeptName}}
            </span>
          </template>
        </el-table-column>
        <!--<el-table-column prop="itemIndex" align="center" label="排序号" show-overflow-tooltip></el-table-column>-->
        <el-table-column prop="state" align="center" label="状态" show-overflow-tooltip width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.state == 0">未提交</span>
            <span v-else-if="scope.row.state == 1"
            >拟定中</span
            >
            <span v-else-if="scope.row.state == 2"
            >拟定审核中</span
            >
            <span v-else-if="scope.row.state == 3"
            >拟定已审核</span
            >
            <span v-else-if="scope.row.state == 4"
            >审核驳回</span
            >
            <span v-else-if="scope.row.state == 5"
            >结果填报中</span
            >
            <span v-else-if="scope.row.state == 6"
            >填报审核中</span
            >
            <span v-else-if="scope.row.state == 7"
            >填报审核驳回</span
            >
            <span v-else-if="scope.row.state == 8"
            >确认中</span
            >
            <span v-else-if="scope.row.state == 10"
            >已结束</span
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <span slot="footer" class="dialog-footer">

     <!-- <el-button type="primary" plain @click="handleConfirm">确定</el-button>-->
      <el-button type="primary" v-if="dialogTitle=='新增人员考核'" plain @click="handleConfirm">确定</el-button>
      <el-button type="primary" v-if="isEdit&&dialogTitle=='编辑'" plain @click="handleConfirm">确定</el-button>
      <el-button type="primary" plain @click="closeDialog()">返回</el-button>
    </span>

    <UserCommonSelect v-if="usercomment" ref="usercomment" @submitfy="submitfy"></UserCommonSelect>
    <FormulateDialog v-if="formulateDialog" ref="formulateDialog" @submitfy="submitfy1"></FormulateDialog>
    <!-- 考核指标库 -->
    <el-dialog title="精准激励指标库" :visible.sync="dialogVisible" width="80%" append-to-body>
      <zhibiaoTable ref="zhibiaoRef" @func="getRow"></zhibiaoTable>
      <span slot="footer" class="dialog-footer">
        <el-button plain type="primary" @click="addZhibiao">添 加</el-button>
        <el-button plain @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
import UserCommonSelect from "@/views/dailyExamine/components/usercomment-selectCopy-zb"; //人员选择的组件
import zhibiaoTable from "@/views/dailyExamine/components/targetIndexTable"; //指标表格
import {
  targetAllFill,
  targetDetail,
  saveFillTarget,
  indexExaminAllDataList,
  targetNeedFill,
  zltest,
  zltestAdd,
  checkitem
} from "@/api/dailyExamine/targetExamine/indicatorFormulation";
import { getObj } from "@/api/admin/user.js";
import FormulateDialog from "./formulateDialog"; //数据提供部门选择组件
import { validatenull } from "@/util/validate"; //判断空
import { remote as remoteDict } from "@/api/admin/dict"; //数据获取方式接口
export default {
  data() {
    return {
      fatherData: {},
      dataList: [], //指标表格数据
      oldDataList:[],//原始表格数据
      visible: false, //最外层弹窗显隐
      dataForm: {}, //表单对象
      multipleSelection: [], //选中的指标
      isEdit: true, //是否编辑
      formulateDialog: false, //数据提供部门/人组件显隐
      canDelete: true, //是否能删除指标
      chooseTarget: [], //选中的指标
      usercomment: false, //人员组件显隐
      dialogVisible: false, //考核指标库显隐
      dialogTitle: "新增人员考核", //弹窗标题
      userData: {}, //登录人信息对象
      dataFromList:[],//数据获取方式列表
        rules:{
            weight: [
                { required: true,message: "请输入数字", trigger: "blur" },
                {type:"number",message:"权重必须为数字值"}],
            score: [
                { required: true,message: "请输入数字", trigger: "blur" },
                {type:"number",message:"得分必须为数字值"}],
        },
    };
  },
  components: {
      UserCommonSelect,
      zhibiaoTable,
      FormulateDialog
  },
  created() {

   },
  watch: {
      // 监听指标选中变化
      multipleSelection: {
          handler(val) {
              if (val.length !== 0) {
                  this.canDelete = false;
              } else {
                  this.canDelete = true;
              }
          },
          deep: true
      },

  },
  methods: {
    // 查询数据详情
    getDataDetail(id) {
      targetDetail(id)
        .then(r => {
          if (r.data.code == 0) {
            this.dataForm = r.data.data;
            this.dataForm.assessTarget = r.data.data.participantList.map(it => {
              return it.assessRealName;
            });
            this.dataForm.assessDeptName = r.data.data.participantList.map(
              it => {
                return it.assessDeptName;
              }
            );
          } else {
            this.$message.error(r.data.msg);
          }
        })
        .catch(err => {});
    },
    // 查询需要自己填写的指标
    getNeedFillTarget(id) {
        indexExaminAllDataList(id)
            .then(r => {
                if (r.data.code == 0) {
                    this.dataList = r.data.data.map((it, index) => {
                        it.renderId = index + 1;
                        return it;
                    });
                    this.oldDataList = this.dataList ;//保留一份原始指标
                    console.log(this.dataList)
                } else {
                    this.$message.error(r.data.msg);
                }
            })

    },

    //   人员展示
    showPerson() {
        this.usercomment = true;
        this.$nextTick(() => {
            this.$refs.usercomment.init(
                "12",
                "sy",
                JSON.stringify(this.options),
                "htcj",
                "新增",
                undefined
            );
        });
    },
    // 展示数据提供部门
    showDataProvide(data, index) {
        this.chooseDeptData = data;
        this.formulateDialog = true;
        this.jsonData = JSON.stringify([{}]);
        this.providerIndex = index;
        this.$nextTick(() => {
            this.$refs.formulateDialog.init("12", "ndts", this.jsonData, "ndcj");
        });
    },
    // 添加指标
    addZhibiao() {
        let tempList = this.chooseTarget.map((it, index) => {
            it.type = it.normLx;
            it.name = it.normName;
            it.formula = it.normGsname;
            it.formulaId = it.normGs;
            it.completeValue =  "手动获取";//it.normGetDate;
            it.keiExplain = it.normSm;
            it.unit = it.normDw;
            it.itemIndex = it.normPx;
            it.normId = it.normId ;
            it.state = 6;
            it.editFlag = 1;
            it.isLiaison = 0;
            it.provideUserId =it.provideUserId;
           /* it.provideDeptId = this.userData.deptId;
            it.provideDeptName = this.userData.deptName;
            it.provideRealName = this.userData.ryName;
            it.provideUserId = this.userData.userId;
            it.provideUserName = this.userData.username;*/
            return it;
        });
        //this.dataList = [...this.dataList, ...Object.assign(tempList)];

        //筛选出重复指标，并做提示
        let normNameList = [] ;
        for(let i = 0; i < tempList.length; i++) {
            let tempArr1 = tempList[i]
            for(let j = 0; j < this.dataList.length; j++) {
                let tempArr2 = this.dataList[j]
                if(parseInt(tempArr2.normId) === parseInt(tempArr1.normId)){
                    normNameList.push(tempArr1.normName);
                    break;
                }
            }
        }
        if (normNameList.length>0){
            this.$message.error("“"+normNameList.toString()+"”不可重复添加") ;
        }

        const arr = [...this.dataList, ...Object.assign(tempList)]; //父子数据合并
        const newArr = arr.reduce(function (tempArr, item) { //去重
            if (tempArr.findIndex((ele) => parseInt(ele.normId) === parseInt(item.normId)) === -1) {
                tempArr.push(item)
            }
            return tempArr
        }, []);
        this.dataList = newArr ; //去重后的数据


        this.dialogVisible = false;
        this.dataList.map((it, index) => {
            it.renderId = index + 1;
        });
        console.log(this.dataList);
    },
    // 子组件穿过来的数据
    getRow(rows) {
        this.chooseTarget = rows;
    },
    // 显示指标表格
    showTarLibrary() {
        this.dialogVisible = true;
        this.$nextTick(() => {
            this.$refs.zhibiaoRef.init(1, 1);
        });
    },
    // 选中指标
    handleSelectionChange(rows) {
        this.multipleSelection = rows;
    },
    // 删除指标
    deleteIndexRow() {
        this.$confirm("是否确认删除", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        })
            .then(() => {
                let temp = [];
                this.multipleSelection.map(it => {
                    this.dataList = this.dataList.filter(itt => {
                        return it.renderId !== itt.renderId;
                    });
                });
                // this.dataList = [...temp];
            })
            .catch(() => {});
    },
    // 数据提供部门选择后的确定
    submitfy1(data) {
        if (this.dialogTitle == "编辑") {
            if (data.selectorgdata.length == 0) {
                this.dataList.map(it => {
                    if (it.renderIndex == this.chooseDeptData.renderIndex) {
                        this.$set(it, "provideRealName", data.tableDataUser[0].ryName);
                        this.$set(it, "provideUserName", data.tableDataUser[0].userCode);
                        this.$set(it, "provideUserId", data.tableDataUser[0].userId);
                        this.$set(it, "provideDeptName", data.tableDataUser[0].deptName);
                        this.$set(it, "provideDeptId", data.tableDataUser[0].deptId);
                        this.$set(it, "isLiaison", 0);
                    }
                });
            } else {
                this.dataList.map(it => {
                    if (it.renderIndex == this.chooseDeptData.renderIndex) {
                        this.$set(it, "provideRealName", data.selectorgdata[0].ryName);
                        this.$set(it, "provideUserName", data.selectorgdata[0].userCode);
                        this.$set(it, "provideUserId", data.selectorgdata[0].userId);
                        this.$set(it, "provideDeptName", data.selectorgdata[0].deptName);
                        this.$set(it, "provideDeptId", data.selectorgdata[0].deptId);
                        this.$set(it, "isLiaison", 1);
                    }
                });
            }
        } else {

            if (data.selectorgdata.length == 0) {
                this.dataList.map(it => {
                    if (it.normId == this.chooseDeptData.normId) {
                        this.$set(it, "provideRealName", data.tableDataUser[0].ryName);
                        this.$set(it, "provideUserName", data.tableDataUser[0].userCode);
                        this.$set(it, "provideUserId", data.tableDataUser[0].userId);
                        this.$set(it, "provideDeptName", data.tableDataUser[0].deptName);
                        this.$set(it, "provideDeptId", data.tableDataUser[0].deptId);
                        this.$set(it, "isLiaison", 0);
                    }
                });
            } else {
                this.dataList.map(it => {
                    if (it.normId == this.chooseDeptData.normId) {
                        this.$set(it, "provideRealName", data.selectorgdata[0].ryName);
                        this.$set(it, "provideUserName", data.selectorgdata[0].userCode);
                        this.$set(it, "provideUserId", data.selectorgdata[0].userId);
                        this.$set(it, "provideDeptName", data.selectorgdata[0].deptName);
                        this.$set(it, "provideDeptId", data.selectorgdata[0].deptId);
                        this.$set(it, "isLiaison", 1);
                    }
                });
            }
        }
    },
    // 确定
    handleConfirm() {

        this.$refs.dataForm.validate(valid => {
            if (valid) {
                let submitDataList = this.dataList.map(it => {
                    delete it.createDeptId;
                    delete it.createDeptName;
                    delete it.createTime;
                    delete it.createUserId;
                    delete it.createUserName;
                    delete it.dataState;
                    delete it.editDeptId;
                    delete it.editDeptName;
                    delete it.editTime;
                    delete it.editUserId;
                    delete it.editUserName;
                    delete it.tenantId;
                    delete it.id;
                    it.assessId = this.fatherData.assessId;
                    return it;
                });

                //验证指标列表中数据提供部门/人不可为空
                let flag = submitDataList.every( it=> {
                    return !validatenull(it.isLiaison) && ( (it.isLiaison==0 && !validatenull(it.provideRealName))||(it.isLiaison==1 && !validatenull(it.provideDeptName)))
                }) ;
                if(!flag){
                    this.$message.error('数据提供部门/人不可空');
                    return ;
                }

                const szValid = /^[1-9]\d*\,\d*|[1-9]\d*$/;
                const fsValid = /^(-)?[1-9][0-9]*$/;
                submitDataList.map(it=>{
                    if(it.weight != null && it.weight !=''){
                        if(!szValid.test(it.weight)){
                            this.$message.error('权重必须为数字值');

                            throw new Error('end') // 终止循环
                        }

                    }
                })


                //验证是否超200字
              /*  let flagTargetValue = submitDataList.every( it=> {
                    return !validatenull(it.finishValue) && it.finishValue.length<=200 ;
                }) ;
                if (!flagTargetValue){
                    this.$message.error('完成值不可为空且不可超过200字');
                    return ;
                }*/

                /* let flagWeight = submitDataList.every( it=> {
                     return !validatenull(it.weight) && (szValid.test(it.weight))
                 }) ;
                 if(!flagWeight){
                     this.$message.error('权重必须为数字值并且不可为空');
                     return ;
                 }*/
                let flagScore = submitDataList.every( it=> {
                    return !validatenull(it.score)
                }) ;
                if(!flagScore){
                    this.$message.error('得分不可为空');
                    return ;
                }
                //原数据和新添加的数据对比，返回非重复值
                const res= this.dataList.filter((e)=>!this.oldDataList.some((e2)=>parseInt(e2.normId)===parseInt(e.normId)))
                let normIds = res.map(it=>{
                    return it.normId ;
                })

                if (normIds.length == 0) { //不做验证
                    saveFillTarget(submitDataList, this.fatherData.id, 1)
                        .then(r => {
                            if (r.data.code == 0) {
                                this.$message.success("填报成功");
                                this.closeDialog();
                                this.$emit("closeDialog");
                                this.$emit("refresh");
                            }
                        })
                        .catch(err => {
                        });
                }else{
                    checkitem(this.fatherData.id, normIds.toString()) //验证新增的指标是否有重复
                        .then(r => {
                                if (!r.data.msg) {
                                    saveFillTarget(submitDataList, this.fatherData.id, 1)
                                        .then(r => {
                                            if (r.data.code == 0) {
                                                this.$message.success("填报成功");
                                                this.closeDialog();
                                                this.$emit("closeDialog");
                                            }
                                        })
                                        .catch(err => {});
                                }else{
                                    this.$message.error(r.data.msg) ;
                                }
                           })
                }

            } else {
                console.log("error submit!!");
                return false;
            }
        });
    },
    // 初始化
    init(data) {
      this.visible = true;
      this.fatherData = data;
      this.getDataDetail(data.id);
      this.getNeedFillTarget(data.id);
      this.getNormDataTypes() ; //数据获取方式列表
    },
    //添加分数
    getScore(row, index){

            if(row.finishValue !=null && row.finishValue !="") {
                zltest(row.id,row.finishValue)
                    .then(r => {
                        this.$set(
                            this.dataList[index],
                            "score",
                            this.numFilter(r.data.data)
                        );
                    })
                    .catch(err => {

                    });
            }else{
                row.score = '';
            }




    },

    //新增指标添加分数
    getScoreAdd(row, index){

            if(row.finishValue !=null && row.finishValue != "" && row.targetValue != null && row.targetValue != "" && row.weight != null && row.weight != "") {
                zltestAdd(row.formulaId,row.targetValue,row.finishValue,row.weight)
                    .then(r => {
                       this.$set(
                          this.dataList[index],
                          "score",
                          this.numFilter(r.data.data)
                        );

                    })
                    .catch(err => {

                    });
            }else{
                row.score = '';
            }
    },

    numFilter(value) {
        const realVal = parseFloat(value).toFixed(2);
        return realVal;
    },
    // 表单提交
    dataFormSubmit() {},
    // 关闭
    closeDialog() {
      this.visible = false;
      this.$emit("closeDialog");
    },
    //数据获取方式列表
    getNormDataTypes(){
        remoteDict("sys_norm_sjhqfs").then(response => {
            this.dataFromList = response.data.data;
        });
    }
  }
};
</script>

<style lang="scss">
</style>
